import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button,Checkbox, Form, Input, message ,Flex} from 'antd';
import { useHistory } from 'react-router-dom';

import { api } from '../../request'
import store from '../../store'
import { setToken } from '../../store/auth'

const Page = () => {

  const history = useHistory();

  const onFinish = (values) => {
    
    api.user.login(values).then(res => {
      if (res.code === 'YES') {
        store.dispatch(setToken(res.token))
        history.push('/home')
        message.success('welcome', 2.5)
      } else {
        message.error(`failed:${res.msg}`, 2.5)
      }
    })
  };

  return (
    <Form
      name="login"
      className='my-form'
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: 'Please input your Username!',
          },
        ]}
      >
        <Input prefix={<UserOutlined />} placeholder="Username" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: 'Please input your Password!',
          },
        ]}
      >
        <Input prefix={<LockOutlined />} type="password"
          placeholder="Password" />
      </Form.Item>
      <Form.Item>
        <Flex justify="space-between" align="center">
          <Form.Item name="remember" valuePropName="checked"
            noStyle>
            <Checkbox>Remember me</Checkbox>
          </Form.Item>
          <a href="::javascript">Forgot password</a>
        </Flex>
      </Form.Item>

      <Form.Item>
        <Button block type="primary"
          htmlType="submit">
          Log in
        </Button>
        or <a href="::javascript">Register now!</a>
      </Form.Item>
    </Form>
  )
};
export default Page;